package com.woparker.kiosk.activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.woparker.kiosk.R;
import com.woparker.kiosk.base.BaseActivity;
import com.woparker.kiosk.bean.LotBean;
import com.woparker.kiosk.bean.MapGroupBean;
import com.woparker.kiosk.bean.NodeBean;
import com.woparker.kiosk.bean.PassableBean;
import com.woparker.kiosk.bean.PlaceBean;
import com.woparker.kiosk.bean.ResultBean;
import com.woparker.kiosk.bean.SlotDTO;
import com.woparker.kiosk.config.Constant;
import com.woparker.kiosk.model.impl.NavigationModelImpl;
import com.woparker.kiosk.presenter.NavigationPresenter;
import com.woparker.kiosk.utils.BitmapUtils;
import com.woparker.kiosk.utils.CommonUtils;
import com.woparker.kiosk.utils.MapDataUtils;
import com.woparker.kiosk.view.PathAnimationView;
import com.woparker.kiosk.view.PinchImageView;
import com.woparker.kiosk.view.QSView;
import com.woparker.kiosk.view.Toasty;

import java.util.ArrayList;
import java.util.List;


public class NavigationActivity extends BaseActivity implements QSView {
    private NavigationPresenter presenter;
    private PinchImageView new_mapView;
    private PathAnimationView pathAnimView;
    private TextView plate;
    private TextView location;
    private TextView nowFloor;
    private TextView enterTime;
    private TextView carFloor;
    private Button returnBt;

    // 下载背景图片
    private Bitmap bgBitmap;
    // 空背景层
    private Bitmap mBackgroundBitmap;
    // 画布
    private Canvas canvas;
    //车位对象
    private SlotDTO lotBean;
    //数据结果对象
    private ResultBean resultBean;
    //地图片对象
    private PlaceBean placeBean;
    private PlaceBean nowPlaceBean;
    //收款码大小
    private final static int QR_CODE_SIZE = 150;
    //是否为同层
    public boolean isSameFloor = true;
    //起点X坐标
    private int startX;
    //起点Y坐标
    private int startY;
    //终点X坐标
    private int tarX = 468;
    //终点Y坐标
    private int tarY = 373;
    //停车位置
    private String parkingSpaces = "";
    //楼层信息
    private String floorName = "";
    //您的位置
    private String yourLocationTag = "您当前的位置";
    //目标位置
    private String tagLocationTag = "通道位置";
    //默认最差路线点数
    private int bestPointsNumber = 10000000;
    //最优点的位置
    private int bestPointsLocation;

    private MapGroupBean mapGroupBean;
    //电梯集合
    private List<PassableBean> passableBeanList = new ArrayList<PassableBean>();
    //最优电梯
    private PassableBean bestPassbleBean;

    @Override
    public View createView() {
        View view = LayoutInflater.from(this).inflate(R.layout.activity_navigation, null);
        return view;
    }

    @Override
    public void initView() {
        presenter = new NavigationPresenter(this, this, new NavigationModelImpl(this));
        new_mapView = findViewById(R.id.new_mapView);
        pathAnimView = findViewById(R.id.pathAnimView);
        presenter.setPathAnimView(pathAnimView);
        plate = findViewById(R.id.plate);
        location = findViewById(R.id.location);
        nowFloor = findViewById(R.id.now_floor);
        enterTime = findViewById(R.id.enter_time);
        carFloor = findViewById(R.id.car_floor);
        returnBt = findViewById(R.id.return_but);
        returnBt.setOnClickListener(v->{
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
        presenter.initBitmap();
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        if (null == intent) {
            return;
        }
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            //测试
            lotBean = (SlotDTO) bundle.getSerializable("SlotDTO");
            resultBean = getBean();
            for (PlaceBean placeItem : resultBean.getPlaces()) {
                if (placeItem.getPlaceId() == resultBean.getPlaceId()) {
                    nowPlaceBean = placeItem;
                    break;
                }
            }
            this.placeBean = nowPlaceBean;
            if (null != this.placeBean) {
                plate.setText(lotBean.getPlate());
                location.setText(lotBean.getPlaceName() + " " + lotBean.getName());
                nowFloor.setText(placeBean.getPlaceId() + " " + placeBean.getName());
                enterTime.setText(CommonUtils.getTime(lotBean.getDate()));
                carFloor.setText(placeBean.getPlaceId() + " " + lotBean.getGarage());
                //根据场地IP判断是否为同一层
//                if (resultBean.getPlaceId() == lotBean.getPlaceId()) {
                    isSameFloor = true;
                    initNavData(resultBean.getStartX(), resultBean.getStartY(), lotBean.getX(), lotBean.getY(), "",
                            lotBean.getPlaceName(), "车辆位置");
//                } else {
//                    isSameFloor = false;
//                }
                //获取对应的地图数组数据
//                    presenter.getMapGroupBean(Constant.URLConstant.getBaseDownloadBGUrl() + this.placeBean.getMap());
                //测试
                MapGroupBean mapGroupBean = new MapGroupBean();
                mapGroupBean.setBlockSize(10);
                mapGroupBean.setCol(121);
                mapGroupBean.setRow(65);
                mapGroupBean.setMap(MapDataUtils.test_map);
                //获取对应的地图数组数据
                getMapGroupData(mapGroupBean);
            }
            else{
                showToast(Toasty.TYPE_NORMAL,"未获取到场地信息");
            }
        }
    }

    public ResultBean getBean(){
        ResultBean resultBean1 = new ResultBean();
        resultBean1.setMsg("OK");
        resultBean1.setCode(1);
        resultBean1.setStartX(77);
        resultBean1.setStartY(213);

        PlaceBean placeBean = new PlaceBean();
        placeBean.setName("场地1");
        placeBean.setPic("");
        placeBean.setMap("");
        placeBean.setPlaceId(0);
        ArrayList<PlaceBean> placeBeans = new ArrayList<>();
        placeBeans.add(placeBean);
        resultBean1.setPlaces(placeBeans);

        ArrayList<LotBean> lotBeans = new ArrayList<>();
        LotBean lotBean = new LotBean();
        lotBean.setPlaceId(0L);
        lotBean.setName("5号车位");
        lotBean.setPlate("粤B667788");
        lotBean.setPlateColor("蓝牌");
        lotBean.setX(652);
        lotBean.setY(328);
        lotBean.setPic("http://www.baidu.com");
        lotBean.setArea("A区");
        lotBean.setUpdateDate(System.currentTimeMillis());
        lotBean.setGarage("3号车库");
        lotBean.setPlaceName("停车场1");
        lotBean.setDate(System.currentTimeMillis());
        lotBeans.add(lotBean);
        resultBean1.setLots(lotBeans);

        ArrayList<PassableBean> passableBeans = new ArrayList<>();
        passableBeans.add(new PassableBean(0L,"",0,0));
        resultBean1.setPassables(passableBeans);
        resultBean1.setTotalElements(1);
        resultBean1.setPage(1);
        return resultBean1;
    }


    @Override
    public void getMapGroupData(MapGroupBean mapGroupBean) {
        this.mapGroupBean = mapGroupBean;
        if (isSameFloor) {
            int[] size = BitmapUtils.getImageSizeFromResource(getResources(), R.mipmap.test_map);
            //测试
            Bitmap bitmap = CommonUtils.getBitmapFromResource(getResources(), R.mipmap.test_map);
            BitmapUtils.RATIO = (float) bitmap.getWidth()/(float) size[0] ;
//            487 908  649 1210
            getMapImage(bitmap);

        } else {
            passableBeanList.clear();
            if (null != resultBean.getPassables()) {
                //寻找电梯
                for (PassableBean passableBean : resultBean.getPassables()) {
                    if (passableBean.getPlaceId() == resultBean.getPlaceId()) {
                        passableBeanList.add(passableBean);
                    }
                }
                //电梯不为空
                if (!passableBeanList.isEmpty()) {
                    for (int i = 0; i < passableBeanList.size(); i++) {
                        //是否遍历到最后一条记录
                        if (i == (passableBeanList.size() - 1)) {
                            presenter.getBestFloor(mapGroupBean, resultBean.getStartX(), resultBean.getStartY(), passableBeanList.get(i).getX(),
                                    passableBeanList.get(i).getY(), i, true);
                        } else {
                            presenter.getBestFloor(mapGroupBean, resultBean.getStartX(), resultBean.getStartY(), passableBeanList.get(i).getX(),
                                    passableBeanList.get(i).getY(), i, false);
                        }
                    }
                }
            } else {
                showToast(Toasty.TYPE_NORMAL, "您还未设置电梯");
            }
        }

    }

    //初始化导航数据
    @Override
    public void initNavData(int startX, int startY, int tarX, int tarY, String floorStr, String parkingStr, String tagStr) {
        this.startX = startX;
        this.startY = startY;
        this.tarX = tarX;
        this.tarY = tarY;
        this.floorName = floorStr;
        this.parkingSpaces = parkingStr;
        this.tagLocationTag = tagStr;
    }

    @Override
    public void setData(String data) {

    }

    @Override
    public void selectedIndex(int itemPostion) {

    }

    @Override
    public void showLoading(String content) {

    }

    @Override
    public void hindLoading() {

    }

    @Override
    public void getMapImage(Bitmap bitmap) {
        bgBitmap = bitmap;
        if (null == bgBitmap) {
            return;
        }
        //创建背景图
        mBackgroundBitmap = Bitmap.createBitmap(bgBitmap.getWidth(),
                bgBitmap.getHeight(), Bitmap.Config.RGB_565);
        canvas = new Canvas();
        canvas.setBitmap(mBackgroundBitmap);

        presenter.drawBestRoot(mapGroupBean, canvas, bgBitmap,
                startX, startY, tarX, tarY,
                yourLocationTag, floorName, tagLocationTag, parkingSpaces);
    }


    @Override
    public void onMapInit() {
        //更新UI地图
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new_mapView.setImageBitmap(mBackgroundBitmap);
            }
        });

    }

    @Override
    public void onQueryBestRoot(int type, int number, List<NodeBean> bestRoots, boolean isLast) {
        switch (type) {
            case 0:
                //单个最优路线查询成功并更新地图UI
                presenter.updataMapUI(canvas);
                break;
            case 1:
                //未获取到最优路线
                Toasty.showToast(this, Toasty.TYPE_NORMAL, "未查询到最优路线");
                break;
            case 2:
                //数据集合处理寻找最优通道点
                if (bestRoots.size() < bestPointsNumber) {
                    bestPointsNumber = bestRoots.size();
                    bestPointsLocation = number;
                }
                if (isLast) {
                    //得到最优电梯对象
                    bestPassbleBean = passableBeanList.get(bestPointsLocation);
                    initNavData(resultBean.getStartX(), resultBean.getStartY(), bestPassbleBean.getX(), bestPassbleBean.getY(), "",
                            bestPassbleBean.getName(), "通道位置");
                    if (null != placeBean) {
                        presenter.getBitmapImage(Constant.URLConstant.getBaseDownloadBGUrl() + placeBean.getPic());
                    }
                }
                break;
        }

    }

    //当前层导航
    public void nowNav() {
        new_mapView.reset();
        //人和车是否处于同一层
        this.placeBean = nowPlaceBean;
        if (isSameFloor) {
            initNavData(resultBean.getStartX(), resultBean.getStartY(), lotBean.getX(), lotBean.getY(), "",
                    lotBean.getPlaceName(), "车辆位置");
        } else {
            if (null == bestPassbleBean) {
                showToast(Toasty.TYPE_NORMAL, "未获取到电梯信息");
                return;
            }
            initNavData(resultBean.getStartX(), resultBean.getStartY(), bestPassbleBean.getX(), bestPassbleBean.getY(), "",
                    bestPassbleBean.getName(), "通道位置");
        }
        if (null != this.placeBean) {
            presenter.getMapGroupBean(Constant.URLConstant.getBaseDownloadBGUrl() + this.placeBean.getMap());
        }
    }

    //另一层导航
    public void otherNav() {
        new_mapView.reset();
        //不在同一层才可以点击另层导航
        if (isSameFloor == false) {
            if (null == bestPassbleBean) {
                showToast(Toasty.TYPE_NORMAL, "未获取到电梯信息");
                return;
            }
            PlaceBean nowPlace = null;
            for (PlaceBean placeItem : resultBean.getPlaces()) {
                if (placeItem.getPlaceId() == lotBean.getPlaceId()) {
                    nowPlace = placeItem;
                    break;
                }
            }
            PassableBean nowPassable = null;
            for (PassableBean passableBean : resultBean.getPassables()) {
                if (!TextUtils.isEmpty(passableBean.getName()) &&
                        passableBean.getPlaceId() == nowPlace.getPlaceId() &&
                        passableBean.getName().equals(bestPassbleBean.getName())) {
                    nowPassable = passableBean;
                    break;
                }
            }

            if (null == nowPlace || null == nowPassable) {
                showToast(Toasty.TYPE_NORMAL, "未获取到相应的场地信息");
                return;
            }

            this.placeBean = nowPlace;
            initNavData(nowPassable.getX(), nowPassable.getY(), lotBean.getX(), lotBean.getY(), nowPassable.getName(),
                    lotBean.getName(), "车辆位置");
            if (null != this.placeBean) {
                presenter.getMapGroupBean(Constant.URLConstant.getBaseDownloadBGUrl() + this.placeBean.getMap());
            }
        }
    }
}
